# -*- coding: utf-8 -*-
import sys
from urllib import urlencode
import json
import urllib2
from oauth_facebook import login

class FQL(object):

    ENDPOINT = 'https://api.facebook.com/method/'

    def __init__(self, access_token=None):
        self.access_token = access_token

    def _fetch(cls, url, params=None):
        conn = urllib2.urlopen(url, data=urlencode(params))
        try:
            return json.loads(conn.read())
        finally:
            conn.close()

    def query(self, q):
        if q.strip().startswith('{'):
            return self.multiquery(q)
        else:
            params = dict(query=q, access_token=self.access_token, format='json')
            url = self.ENDPOINT + 'fql.query'
            return self._fetch(url, params=params)

    def multiquery(self, q):
        params = dict(queries=q, access_token=self.access_token, format='json')
        url = self.ENDPOINT + 'fql.multiquery'
        return self._fetch(url, params=params)

if __name__ == '__main__':
    try:
        access_token = open('out/facebook.access_token').read()
    except IOError, e:

        print >> sys.stderr, \
           "Não foi possivel ler ou carregar o arquivo contendo o access_token de acesso !!"
        access_token = login()

    query = 'select name,sex from user where uid in (select target_id from  connection where source_id = me() and target_type ="user")'
    fql = FQL(access_token=access_token)
    result = fql.query(query)
    print json.dumps(result, indent=4)
